import {
	baseUrl
} from "./baseurl.js";
import {
	decryptHex,
	decryptBase64,
	encryptBase64
} from "@/utils/aes.js";
const install = (Vue) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: baseUrl,
		dataType: 'json',
		header: {
			'content-type': 'application/json',
		},
	});
	Vue.prototype.$u.http.interceptor.request = async (config) => {
		const token = uni.getStorageSync('clinetToken');
		if (token) config['header'].publictoken = token;
		console.log(config.data, '接口:',config.url);
		config.data = encryptBase64(JSON.stringify(config.data))
		return config;
	}

	Vue.prototype.$u.http.interceptor.response = (res) => {
		let data = decryptHex(res + '');
		const dataAxios = JSON.parse(data);
		console.log("response", dataAxios);
		if (dataAxios.code == 200) {
			return dataAxios;
		} else if (dataAxios.code === 401 && /登录/.test(dataAxios.message)) {
			Vue.prototype.$u.toast(dataAxios.message);
		} else if (dataAxios.code === 403 && /权限/.test(dataAxios.message)) {
			Vue.prototype.$u.toast(dataAxios.message);
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/mine/index'
				})
			}, 800)
		} else if (dataAxios.code === 509) {
			Vue.prototype.$u.toast('登录已失效，请重新登录');
			uni.removeStorageSync('clinetToken');
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}, 800)
			return false;
		}else if (dataAxios.code === 500) {
			Vue.prototype.$u.toast(dataAxios.message);
			uni.showToast({
				title: dataAxios.message,
				image: "/static/icon/error.png"
			})
			return false;
		} else {
			Vue.prototype.$u.toast(dataAxios.message);
			return false;
		}
	}
}

export default {
	install
}